package com.tsystems.train.validator;

import java.util.Set;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;



public class MyValidator {

	public static boolean validate(Object entity) {

		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		Validator validator = vf.getValidator();

		String message = validate(entity, validator);
		if (message != null) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Validation error", message));
			return false;
		}

		return true;
	}

	public static String validate(Object object, Validator validator) {
		Set<ConstraintViolation<Object>> constraintViolations = validator
				.validate(object);
		String resultString = null;

		if (constraintViolations.size() > 0) {
			resultString = "";

			for (ConstraintViolation<Object> cv : constraintViolations) {
				resultString += cv.getMessage() + "\n";
			}
		}
		return resultString;
	}
	
	
}
